// 引入scp2
const client = require("scp2");
const ssh2 = require("ssh2");

const { Client } = ssh2;

const server = {
  host: "112.124.2.167", // 服务器ip
  username: "root", // 用户名
  password: "Yjw1262793484", // 密码
  path: "/www/wwwroot/coral/frontend", // 项目路径
  port: "22", // 端口一般默认22
  locaPath: "./.next.zip", // 本地dist压缩包
};
// 建立连接的
const conn = new Client();
console.log("正在建立连接");

// 检测是否存在该目录，如果没有该目录就创建
const checkDirectory = () => {
  conn.exec(`mkdir ${server.path}`, (err, stream) => {
    stream.on("close", () => {
      // 上传
      rimraf();
    });
  });
};

// 删除文件
const rimraf = () => {
  conn.exec(`rm -rf ${server.path}/.next.zip`, (err, stream) => {
    stream.on("close", () => {
      // 上传
      conn.exec(`rm -rf ${server.path}/.next`, (err, stream) => {
        stream.on("close", () => {
          console.log(`已删除旧.next文件夹文件，开始上传`);
          upload();
        });
      });
    });
  });
};

// 上传
const upload = () => {
  client.scp(
    server.locaPath,
    {
      host: server.host,
      port: server.port,
      username: server.username,
      password: server.password,
      path: server.path,
    },
    (err) => {
      if (!err) {
        console.log("压缩包上传成功");
        // 解压
        unzip();
      } else {
        console.log("err", err);
      }
    }
  );
};

// 解压
const unzip = () => {
  conn.exec(
    `unzip -o -d ${server.path}/.next ${server.path}/.next.zip`,
    (err, stream) => {
      stream.on("close", () => {
        console.log("解压成功");
        console.log("项目部署成功");
        // 结束
        end();
      });
    }
  );
};

// 结束运行
const end = () => {
  conn.end();
  process.exit();
};

conn
  .on("ready", () => {
    console.log("已连接");
    // 解压
    checkDirectory();
    return null;
  })
  .connect({
    host: server.host,
    port: server.port,
    username: server.username,
    password: server.password,
    // privateKey: '' // 私秘钥
  });
